/**
 * Copyright (c) 2016 Lenovo Group
 * All Rights Reserved.
 * 
 * Project Name:app-gateway
 * Create Time: 2016年1月19日 上午10:34:43
 */
package com.lenovo.lmrp.server.appgateway.util;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.UUID;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * token Util
 * @author zhangzhenga
 *
 */
public class TokenGenerator {

    private static final Logger log = LoggerFactory.getLogger(TokenGenerator.class);

    private static final char[] hexCode = "0123456789abcdef".toCharArray();

    public static String toHexString(byte[] data) {
        if (data == null) {
            return null;
        }
        StringBuilder r = new StringBuilder(data.length * 2);
        for (byte b : data) {
            r.append(hexCode[(b >> 4) & 0xF]);
            r.append(hexCode[(b & 0xF)]);
        }
        return r.toString();
    }

    private String generateValue(String param) {
        MessageDigest algorithm;
        try {
            algorithm = MessageDigest.getInstance("MD5");
            algorithm.reset();
            algorithm.update(param.getBytes());
            byte[] messageDigest = algorithm.digest();
            return toHexString(messageDigest);
        }
        catch (NoSuchAlgorithmException e) {
            // TODO Auto-generated catch block
            log.error("Token cannot be generated!", e);
            return null;
        }

    }

    public String accessToken() {
        return generateValue(UUID.randomUUID().toString());
    }

    public String refreshToken() {
        return generateValue(UUID.randomUUID().toString());
    }
}
